package Zhang7;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.*;
class Ticket {
    private int count =3;
    //售卖总票数
    private Lock lock=new ReentrantLock();//互斥锁
    public void sale(){
//售票业务
        this.lock.lock();
//资源锁定
        try {
            if (this.count > 0){
//有剩余票数
                TimeUnit.SECONDS.sleep(1);
//模拟操作延迟
                System.out.println("【"+Thread.currentThread().getName()+ "】卖票，剩余票数："+ this.count--);
            }else {
                System.err.println("【"+ Thread.currentThread().getName()+ "】票已卖完了，明天再来！");}
            }catch (Exception e) {
        }finally {
            this.lock.unlock();
//解除锁定
        }
    }
}
public class ReentrantLockZhang7{
    public static void main(String[] args) throws Exception{
        Ticket ticet = new Ticket();
//对象实例化
        for (int x = 0;x< 5; x++){
//创建售卖线程
            new Thread(() ->{
                ticet.sale();
//售票处理
            },"售票员-" + x).start();
        }
    }
}
